package com.service;

import com.alibaba.fastjson.JSONObject;
import com.data.DataService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.model.rec.RecDataResultVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import com.util.JsonUtil;

import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

@Service
public class YpRecService implements InitializingBean {

    private static Logger logger = LoggerFactory.getLogger(YpRecService.class);

    public HttpHeaders DEFAULT_JSON_HEADER;

    public HttpHeaders DEFAULT_JSON_HEADER_UTF8;

    public YpRecService(){
        DEFAULT_JSON_HEADER = new HttpHeaders();
        MediaType jsontype = MediaType.APPLICATION_FORM_URLENCODED;
        DEFAULT_JSON_HEADER.setContentType(jsontype);


        DEFAULT_JSON_HEADER_UTF8 = new HttpHeaders();
        DEFAULT_JSON_HEADER_UTF8.setContentType(MediaType.APPLICATION_JSON_UTF8);

    }

    public RecDataResultVO predictNew(String cutImgName, Integer x1, Integer x2, Integer y1, Integer y2,
                                      String uuidFileName, Integer branchId){


        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();

        SortedMap<String, String> map = new TreeMap<>();
        map.put("branchId", branchId.toString());
        map.put("uuidFileName", uuidFileName);
        map.put("x1", x1.toString());
        map.put("x2", x2.toString());
        map.put("y1", y1.toString());
        map.put("y2", y2.toString());
        map.put("cutImgName", cutImgName);
        MultiValueMap postMap = new LinkedMultiValueMap();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            postMap.add(entry.getKey(),entry.getValue());
        }

        try {
            logger.info(JsonUtil.toJson(map));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        headers.add("Content-Type", "application/x-www-form-urlencoded");
        HttpEntity requestBody = new HttpEntity(postMap, headers);
        ResponseEntity<String> resp = restTemplate.postForEntity(DataService.localRecUrl +"/predictNew", requestBody, String.class);
        String result = resp.getBody();

        logger.info(result);

        RecDataResultVO json = JSONObject.parseObject(result, RecDataResultVO.class);

        return json;
    }

    public boolean delImg(String filename, Integer branchId, Integer productId)throws Exception{

        if (!filename.startsWith("http")) {
            filename = filename.replace(DataService.imgPath, DataService.localImgFilePath);
            filename = filename.replace("/com/data/html/", "/code/images/");
        }
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();

        SortedMap<String, String> map = new TreeMap<>();
        map.put("filepath", filename);
        map.put("branchId", branchId.toString());
        map.put("productId", productId.toString());
        MultiValueMap postMap = new LinkedMultiValueMap();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            postMap.add(entry.getKey(),entry.getValue());
        }

        logger.info("delImg===param=={}", JsonUtil.toJson(postMap));
        headers.add("Content-Type", "application/x-www-form-urlencoded");
        HttpEntity requestBody = new HttpEntity(postMap, headers);
        ResponseEntity<String> resp = restTemplate.postForEntity(DataService.localRecUrl+"/delImg", requestBody, String.class);
        String result = resp.getBody();

        logger.info("delImg===result==", result);

        if ("0".equals(result)) {
            return true;
        }
        return false;
    }

    public boolean addImg(String filename, Integer branchId, Integer productId){
        if (!filename.startsWith("http")) {
            filename = filename.replace(DataService.imgPath, DataService.localImgFilePath);
            filename = filename.replace("/com/data/html/", "/code/images/");
        }

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();

        SortedMap<String, String> map = new TreeMap<>();
        map.put("filepath", filename);
        map.put("branchId", branchId.toString());
        map.put("productId", productId.toString());
        MultiValueMap postMap = new LinkedMultiValueMap();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            postMap.add(entry.getKey(),entry.getValue());
        }

        try {
            logger.info("addImg,url == {}", DataService.localRecUrl+"/addImg");
            logger.info(JsonUtil.toJson(map));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        headers.add("Content-Type", "application/x-www-form-urlencoded");
        HttpEntity requestBody = new HttpEntity(postMap, headers);
        ResponseEntity<String> resp = restTemplate.postForEntity(DataService.localRecUrl+"/addImg", requestBody, String.class);
        String result = resp.getBody();

        logger.info("addImg result=={}", result);

        if ("0".equals(result)) {
            return true;
        }else {
            return false;
        }
    }

    public void addProductImg(String filename, Integer productId, Integer branchId){
        if (!filename.startsWith("http")) {
            filename = filename.replace(DataService.imgPath, DataService.localImgFilePath);
            filename = filename.replace("/com/data/html/", "/code/images/");
        }

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();

        SortedMap<String, String> map = new TreeMap<>();
        map.put("filepath", filename);
        map.put("branchId", branchId.toString());
        map.put("productId", productId.toString());
        MultiValueMap postMap = new LinkedMultiValueMap();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            postMap.add(entry.getKey(),entry.getValue());
        }

        try {
            logger.info(JsonUtil.toJson(map));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        headers.add("Content-Type", "application/x-www-form-urlencoded");
        HttpEntity requestBody = new HttpEntity(postMap, headers);
        ResponseEntity<String> resp = restTemplate.postForEntity(DataService.localRecUrl+"/addProductImg", requestBody, String.class);
        String result = resp.getBody();

        logger.info(result);

//        JSONObject json = JSONObject.parseObject(result);
    }

    public boolean addProductImg(Integer productId, Integer branchId){

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();

        SortedMap<String, String> map = new TreeMap<>();
        map.put("productId", productId.toString());
        map.put("branchId", branchId.toString());
        MultiValueMap postMap = new LinkedMultiValueMap();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            postMap.add(entry.getKey(),entry.getValue());
        }

        try {
            logger.info("addProductImg:{}", JsonUtil.toJson(map));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        headers.add("Content-Type", "application/x-www-form-urlencoded");
        HttpEntity requestBody = new HttpEntity(postMap, headers);
        ResponseEntity<String> resp = restTemplate.postForEntity(DataService.localRecUrl+"/addProduct", requestBody, String.class);
        String result = resp.getBody();

        logger.info(result);

        if ("0".equals(result)) {
            return true;
        }
        return false;
    }

    public boolean delProduct(Integer productId, Integer branchId){

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();

        SortedMap<String, String> map = new TreeMap<>();
        map.put("productId", productId.toString());
        map.put("branchId", branchId.toString());
        MultiValueMap postMap = new LinkedMultiValueMap();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            postMap.add(entry.getKey(),entry.getValue());
        }

        try {
            logger.info("delProduct:{}", JsonUtil.toJson(map));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        headers.add("Content-Type", "application/x-www-form-urlencoded");
        HttpEntity requestBody = new HttpEntity(postMap, headers);
        ResponseEntity<String> resp = restTemplate.postForEntity(DataService.localRecUrl+"/delProduct", requestBody, String.class);
        String result = resp.getBody();

        logger.info(result);

        if ("0".equals(result)) {
            return true;
        }
        return false;
    }

    public boolean delProductAndFiles(Integer productId, Integer branchId){

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();

        SortedMap<String, String> map = new TreeMap<>();
        map.put("productId", productId.toString());
        map.put("branchId", branchId.toString());
        MultiValueMap postMap = new LinkedMultiValueMap();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            postMap.add(entry.getKey(),entry.getValue());
        }

        try {
            logger.info("delProduct:{}", JsonUtil.toJson(map));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        headers.add("Content-Type", "application/x-www-form-urlencoded");
        HttpEntity requestBody = new HttpEntity(postMap, headers);
        ResponseEntity<String> resp = restTemplate.postForEntity(DataService.localRecUrl+"/delProductAndFile", requestBody, String.class);
        String result = resp.getBody();

        logger.info(result);

        if ("0".equals(result)) {
            return true;
        }
        return false;
    }

    public boolean delAllImg(Integer branchId){

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();

        SortedMap<String, String> map = new TreeMap<>();
        map.put("branchId", branchId.toString());
        MultiValueMap postMap = new LinkedMultiValueMap();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            postMap.add(entry.getKey(),entry.getValue());
        }

        try {
            logger.info("delAllImg:{}", JsonUtil.toJson(map));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        headers.add("Content-Type", "application/x-www-form-urlencoded");
        HttpEntity requestBody = new HttpEntity(postMap, headers);
        ResponseEntity<String> resp = restTemplate.postForEntity(DataService.localRecUrl+"/delAllImg", requestBody, String.class);
        String result = resp.getBody();

        logger.info(result);

        if ("0".equals(result)) {
            return true;
        }
        return false;
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        /*if (this.localIpAddress != null) {
            Condition condition = new Condition(Recip.class);
            condition.or().andEqualTo("ipType", 1);
            List<Recip> recipList = recipMapper.selectByCondition(condition);

            if (recipList != null && recipList.size() > 0) {
                for (Recip recip : recipList) {
                    RestTemplate restTemplate = new RestTemplate();
                    HttpHeaders headers = new HttpHeaders();

                    SortedMap<String, String> map = new TreeMap<>();
                    map.put("ip", recip.getAddress());
                    MultiValueMap postMap = new LinkedMultiValueMap();
                    for (Map.Entry<String, String> entry : map.entrySet()) {
                        postMap.add(entry.getKey(),entry.getValue());
                    }

                    try {
                        logger.info("addIp:{}", JsonUtil.toJson(map));
                    } catch (JsonProcessingException e) {
                        e.printStackTrace();
                    }
                    headers.add("Content-Type", "application/x-www-form-urlencoded");
                    HttpEntity requestBody = new HttpEntity(postMap, headers);
                    ResponseEntity<String> resp = restTemplate.postForEntity("http://"+this.localIpAddress+":5001/addIp", requestBody, String.class);
                    String result = resp.getBody();

                    logger.info("addIp result:{}",result);
                }
            }
        }*/
    }
}
